<template>
  <div class="app-container">
    <div class="cardBox">
      <el-row :gutter="10">
        <el-col :span="3">
          <el-button @click="gobackWay" type="text" icon="el-icon-arrow-left"
            style="color: rgba(0, 0, 0, 0.85)">返回</el-button>
          <el-divider direction="vertical"></el-divider>
          <span>选品</span></el-col>
        <el-col :span="21">
          <el-form ref="form" :inline="true" :model="supplierSearchForm" label-width="80px">
            <el-form-item label="供应商">
              <el-select v-model="supplierSearchForm.supplier_id" placeholder="请选择供应商" clearable>
                <el-option v-for="item in supplierList" :key="item.id" :label="item.supplier_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input v-model="supplierSearchForm.goods_name" placeholder="请输入商品名称" clearable />
            </el-form-item>
            <!-- <el-form-item label="商品类目">
              <el-cascader
                clearable
                v-model="supplierSearchForm.category_id"
                :options="typeDataList"
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  value: 'id',
                  label: 'category_name',
                }"
                placeholder="请选择类目ID"
              ></el-cascader>
            </el-form-item> -->
            <el-form-item style="float: right">
              <el-button @click="getSupplierListWay" type="primary" size="mini" icon="el-icon-search">搜索</el-button>
              <el-button @click="resettingSupplier" type="primary" size="mini" icon="el-icon-refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div class="cardBox" style="margin-top: 30px">
      <div class="box" style="padding-right: 20px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-table :header-cell-style="{
              'background-color': '#f3f8fe',
              color: '#606266',
              height: '50px',
            }" ref="multipleTable" v-loading="supplierGoodsListLoading" :data="supplierGoodsList"
              @selection-change="handleSelectionChange">
              <el-table-column label="供货商" align="center" prop="supplier_name" />
              <el-table-column label="商品id" align="center" prop="id" />
              <el-table-column label="商品名称" align="center" prop="goods_name" />
              <el-table-column label="商品图" align="center" prop="main_image">
                <template slot-scope="scope">
                  <div style="width: 40px; height: 40px; margin: 0 auto">
                    <el-image v-if="scope.row.main_image" :src="scope.row.main_image"
                      :preview-src-list="[scope.row.main_image]" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="零售价" align="center" prop="retail_price" />
              <el-table-column label="成本价" align="center" prop="cost_price" />
              <el-table-column label="库存" align="center" prop="CountRepertory" />
              <el-table-column label="商品类目" align="center" prop="inventory">
                <template slot-scope="scope">
                  <el-tag style="margin: 0 3px" size="mini" v-if="scope.row.category1_name">{{ scope.row.category1_name
                  }}</el-tag>
                  <el-tag style="margin: 0 3px" size="mini" v-if="scope.row.category2_name">{{ scope.row.category2_name
                  }}</el-tag>
                  <el-tag style="margin: 0 3px" size="mini" v-if="scope.row.category3_name">{{ scope.row.category3_name
                  }}</el-tag>
                  <el-tag style="margin: 0 3px" size="mini" v-if="scope.row.category4_name">{{ scope.row.category4_name
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200px" fixed="right" align="center">
                <template slot-scope="scope">
                  <el-button type="success" size="mini" @click="addSelectedGoodsWay(scope.row)">加入选品库</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row style="text-align: right">
          <pagination v-show="supplierTotal > 0" :total="supplierTotal" :page.sync="supplierSearchForm.page"
            :limit.sync="supplierSearchForm.count" @pagination="getSupplierListWay" />
        </el-row>
      </div>
      <div class="divider"></div>
      <!-- <div class="box" style="padding-left: 20px">
        <div class="title">当前已选商品</div>
        <el-scrollbar style="height: 650px">
          <div class="container">占位</div>
        </el-scrollbar>
      </div> -->
    </div>
    <el-dialog :close-on-click-modal="false" title="配置商品规则" :visible.sync="configurationDialog" width="900px"
      @close="configuratioClose">
      <div style="position: relative" v-loading="addLoding">
        <el-tabs v-model="activeName">
          <el-tab-pane label="商品规格" name="商品规格">
            <div class="title">商品信息</div>
            <el-row :gutter="20">
              <el-form :model="SKUform" :rules="SKUformRules" ref="SKUform" label-width="110px" class="demo-ruleForm">
                <el-col :span="11">
                  <el-form-item label="商品名称" prop="goodsName">
                    <el-input disabled v-model="SKUform.goodsName" placeholder="商品名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="商品Id" prop="id">
                    <el-input disabled v-model="SKUform.id" placeholder="商品Id"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="规格名称" prop="id">
                    <el-input disabled v-model="SKUform.sku_name" placeholder="规格名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="规格图片" prop="id">
                    <div style="width: 40px; height: 40px; margin: 0 auto">
                      <el-image v-if="SKUform.sku_Img_Url" :src="SKUform.sku_Img_Url"
                        :preview-src-list="[SKUform.sku_Img_Url]" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="库存数量" prop="inventory">
                    <el-input type="number" v-model="SKUform.inventory" min="0" placeholder="库存数量">
                      <template slot="append">
                        <el-popover placement="top-start" trigger="hover">
                          <p style="font-size: 12px">
                            当前商品添加到选品库时需要增加多少库存
                          </p>
                          <el-button slot="reference" icon="el-icon-info"></el-button>
                        </el-popover>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="11">
                  <el-form-item label="提货价格" prop="take_delivery_price">
                    <el-input
                      type="number"
                      min="0"
                      v-model="SKUform.take_delivery_price"
                      placeholder="提货价格"
                    ></el-input>
                  </el-form-item>
                </el-col> -->
                <el-col :span="11">
                  <el-form-item label="提货券价格" prop="voucher_price">
                    <el-input type="number" min="0" v-model="SKUform.voucher_price" placeholder="提货券价格"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="平台分类" prop="gc_id">
                    <el-cascader v-model="gc_id" :options="typeDataList" :props="{
                      expandTrigger: 'hover',
                      checkStrictly: true,
                      value: 'id',
                      label: 'name',
                    }" @change="handleChange" placeholder="请选择平台分类"></el-cascader>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-row>
            <div class="title">价格参考</div>
            <el-row :gutter="20">
              <el-form :model="suggestionForm" :rules="suggestionFormRules" ref="suggestionForm" label-width="140px"
                class="demo-ruleForm">
                <el-col :span="22">
                  <el-form-item label="现金参考价" prop="retail_price">
                    <el-input type="number" min="0" v-model.trim="suggestionForm.retail_price" maxlength="20" clearable
                      show-word-limit placeholder="请输入现金参考价"></el-input>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="11">
                  <el-form-item label="积分参考价" prop="integral_price">
                    <el-input
                      type="number"
                      min="0"
                      clearable
                      maxlength="11"
                      show-word-limit
                      v-model.trim="suggestionForm.integral_price"
                      placeholder="请输入积分参考价"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="积分参考手续费" prop="integral_scale">
                    <el-input
                      type="number"
                      min="0"
                      clearable
                      maxlength="11"
                      show-word-limit
                      v-model.trim="suggestionForm.integral_scale"
                      placeholder="请输入积分参考手续费"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="提货券参考价" prop="voucher_price">
                    <el-input
                      clearable
                      type="number"
                      min="0"
                      maxlength="11"
                      show-word-limit
                      v-model.trim="suggestionForm.voucher_price"
                      placeholder="请输入提货券参考价"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="提货券参考手续费" prop="voucher_scale">
                    <el-input
                      clearable
                      type="number"
                      min="0"
                      maxlength="11"
                      show-word-limit
                      v-model.trim="suggestionForm.voucher_scale"
                      placeholder="请输入提货券参考手续费"
                    ></el-input>
                  </el-form-item>
                </el-col> -->
              </el-form>
              <el-col :span="24" style="text-align: right">
                <el-button @click="configuratioClose">取 消</el-button>
                <el-button type="primary" @click="nextStep()">下一步</el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="针对用户的规则" name="针对用户的规则">
            <el-row :gutter="20">
              <el-form :model="for_user_infoForm" :rules="for_user_infoRules" ref="for_user_infoForm" label-width="110px"
                class="demo-ruleForm">
                <!-- <el-col :span="24">
                  <el-form-item label="支付类型" prop="type">
                    <el-radio
                      v-for="(item, index) in payTypeList"
                      :key="index"
                      v-model="for_user_infoForm.pay_type"
                      :label="item.tag_value"
                      size="mini"
                      >{{ item.tag_name }}</el-radio
                    >
                  </el-form-item>
                </el-col> -->
                <el-col :span="11">
                  <el-form-item label="销售倍数区间" prop="sales_multiplier">
                    <el-input v-model="for_user_infoForm.sales_multiplier" maxlength="3" show-word-limit
                      placeholder="请输入销售倍数区间" clearable />
                    <span style="font-size: 12px; color: #ccc; letter-spacing: 1px">例:1-5,销量会乘以1-5随机数</span>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="关联用户标签" prop="related_user_tag">
                    <el-select v-model="related_user_tag" multiple placeholder="请选择用户标签">
                      <el-option-group v-for="group in labelList" :key="group.label" :label="group.category_name">
                        <el-option v-for="item in group.child" :key="item.id" :label="item.tag_name" :value="item.id" />
                      </el-option-group>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="关联用户分组" prop="related_user_group">
                    <el-select clearable multiple v-model="related_user_group" placeholder="请选择分组">
                      <el-option v-for="item in userGroupList" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="关联用户关系" prop="invitation_relationship">
                    <el-select v-model="invitation_relationship" style="width: 100%" filterable multiple remote clearable
                      reserve-keyword placeholder="请输入手机号(查找用户)" :remote-method="remoteUserMethodWay"
                      :loading="selectLoading">
                      <el-option v-for="item in userList" :key="item.id" :label="item.nickname + '(' + item.mobile + ')'"
                        :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="关联省市区地域" prop="area_id">
                    <el-cascader v-model="cascaderRegList" style="width: 100%" :options="regionList" collapse-tags :props="{
                      expandTrigger: 'hover',
                      multiple: true,
                      value: 'id',
                      label: 'name',
                      children: 'children',
                      checkStrictly: true,
                    }" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="是否优选推荐" prop="is_recommendation">
                    <el-radio v-model="for_user_infoForm.is_recommendation" :label="1" size="mini">是</el-radio>
                    <el-radio v-model="for_user_infoForm.is_recommendation" :label="0" size="mini">否</el-radio>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="是否限购" prop="is_restricted">
                    <el-radio v-model="for_user_infoForm.is_restricted" :label="1" size="mini">是</el-radio>
                    <el-radio v-model="for_user_infoForm.is_restricted" :label="0" size="mini">否</el-radio>
                  </el-form-item>
                </el-col>
                <el-col v-if="for_user_infoForm.is_restricted == 1" :span="11">
                  <el-form-item label="每日限购数量" prop="daily_purchase_limit">
                    <el-input v-model="for_user_infoForm.daily_purchase_limit" onkeyup="value=value.replace(/\D/g,'')"
                      placeholder="请输入限购数量" clearable />
                  </el-form-item>
                </el-col>
                <el-col v-if="for_user_infoForm.is_restricted == 1" :span="11">
                  <el-form-item label="用户总限购数量" prop="total_purchase_limit">
                    <el-input type="number" v-model="for_user_infoForm.total_purchase_limit"
                      onkeyup="value=value.replace(/\D/g,'')" placeholder="请输入限购数量" clearable />
                  </el-form-item>
                </el-col>
              </el-form>
              <el-col :span="24" style="text-align: right">
                <el-button @click="configuratioClose">取 消</el-button>
                <el-button type="primary" @click="nextStep()">下一步</el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="针对商户的规则" name="针对商户的规则">
            <el-row :gutter="20">
              <el-form :model="for_mer_infoForm" :rules="for_mer_infoRules" ref="for_mer_infoForm" label-width="110px"
                class="demo-ruleForm">
                <!-- <el-col :span="24">
                  <el-form-item label="提货类型" prop="type">
                    <el-radio
                      v-for="(item, index) in payTypeList"
                      :key="index"
                      v-model="for_mer_infoForm.pay_type"
                      :label="item.tag_value"
                      size="mini"
                      >{{ item.tag_name }}</el-radio
                    >
                  </el-form-item>
                </el-col> -->
                <el-col :span="11">
                  <el-form-item label="当前可选商户" prop="sales_multiplier">
                    <el-select v-model="for_mer_infoForm.selection_limit" style="width: 100%" filterable multiple remote
                      clearable reserve-keyword placeholder="请输入商户手机号(查找商户)" :remote-method="remoteMethodWay"
                      :loading="selectLoading">
                      <el-option v-for="item in MerchantList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="改价限制类型" prop="change_price_limittype">
                    <el-radio v-for="(item, index) in [
                      { tag_value: 1, tag_name: '不限制' },
                      { tag_value: 2, tag_name: '不可改价' },
                      { tag_value: 3, tag_name: '需在规定范围内改价' },
                      { tag_value: 4, tag_name: '只允许增加建议零售价' },
                      { tag_value: 5, tag_name: '只允许减少建议零售价' },
                    ]" :key="index" v-model="for_mer_infoForm.change_price_limit.type" :label="item.tag_value"
                      size="mini">{{ item.tag_name }}</el-radio>
                  </el-form-item>
                </el-col>
                <el-col :span="11" v-if="for_mer_infoForm.change_price_limit.type == 3 ||
                  for_mer_infoForm.change_price_limit.type == 5
                  ">
                  <el-form-item label="可减少比例" prop="decrement">
                    <el-input clearable type="number" min="0" maxlength="11" show-word-limit v-model.trim="decrement"
                      placeholder="请输入可减少比例"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11" v-if="for_mer_infoForm.change_price_limit.type == 3 ||
                  for_mer_infoForm.change_price_limit.type == 4
                  ">
                  <el-form-item label="可增加比例" prop="increment">
                    <el-input clearable type="number" min="0" maxlength="11" show-word-limit v-model.trim="increment"
                      placeholder="请输入可增加比例"></el-input>
                  </el-form-item>
                </el-col>
              </el-form>
              <el-col :span="24" style="text-align: right">
                <el-button @click="configuratioClose">取 消</el-button>
                <el-button type="primary" @click="nextStep()">提交</el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 选品sku列表弹框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="isShowSkuDialog" width="60%"
      @close="closeDialog">
      <el-table ref="multipleTable" v-loading="isLoadingSku" :data="supplierGoodsSkuList" border stripe
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" />
        <el-table-column label="商品ID" align="center" prop="goods_id" width="100" />
        <el-table-column label="规格名称" align="center" prop="sku_name" />
        <el-table-column label="零售价" align="center" prop="retail_price" width="100" />
        <el-table-column label="当前库存" align="center" prop="inventory" width="100" />
        <el-table-column label="选择库存" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.chooseInventory" size="normal" :min="1" :max="scope.row.inventory"
              :step="1" :controls="true" controls-position="both" />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import {
  goodslist,
  supplierLists,
  getGoodsProductList,
  GoodsCateList,
  getSupplierGoodsInfo,
} from "@/api/supplier/index";
import { getCategoryList } from "@/api/commodity/index";
import { getMerchantList } from "@/api/merchant/index";
import {
  selectionadd,
  addselection,
  editselection,
  detailSelection,
} from "@/api/merchant/index";
import { getDictionaryTypeList } from "@/api/index";
import {
  getTagCategoryAll,
  getgroupList,
  getRegionList,
  getUserList,
} from "@/api/user/index";
export default {
  name: "AddSelectGoods",
  components: {},
  data() {
    return {
      id: "",
      isLoadingSku: false,
      title: "选品sku",
      typeDataList: [],
      payTypeList: [],
      labelList: [],
      userGroupList: {},
      regionList: [],
      MerchantList: [],
      userList: [],
      isShowSkuDialog: false, // 是否显示选品sku弹框
      supplierSearchForm: {
        supplier_id: "",
        goods_name: "",
        category_id: "",
        page: 1,
        count: 10,
        status: 1,
      }, // 供应商商品搜索表单
      supplierGoodsListLoading: false, // 获取供应商产品加载状态控制器
      supplierGoodsList: [], // 供应商商品列表
      supplierTotal: 0,
      supplierGoodsSkuList: [], // 供应商产品规格列表
      supplierList: [], // 供应商列表

      // 加入选品库弹框控制器
      configurationDialog: false,
      // 加入选品库加载框
      addLoding: false,
      // 当前配置的是那个配置
      activeName: "商品规格",
      // 商品信息
      SKUform: {
        goodsName: "",
        id: "",
        inventory: "",
        take_delivery_price: "",
        voucher_price: "",
        gc_id: "",
      },
      // 平台类目回显
      gc_id: [],
      SKUformRules: {
        goodsName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        inventory: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
              } else {
                let req = /^[0-9]+$/;
                if (req.test(value)) {
                  callback();
                } else {
                  callback(new Error("必须是整数"));
                }
                callback();
              }
            },
            trigger: "change",
          },
        ],
        take_delivery_price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value == "") {
                callback(new Error("请填写提货价格"));
              } else {
                let req = /^\d+(\.\d{1,2})?$/;
                if (req.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多只能保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        voucher_price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请填写提货券价格"));
              } else {
                let req = /^\d+(\.\d{1,2})?$/;
                if (req.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多只能保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        gc_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.gc_id.length == 0) {
                callback(new Error("请选择平台分类"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      // 商品参考价格
      suggestionForm: {
        retail_price: "",
        integral_price: "",
        integral_scale: "",
        voucher_price: "",
        voucher_scale: "",
      },
      suggestionFormRules: {
        retail_price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请填写现金参考价"));
              } else {
                let req = /^\d+(\.\d{1,2})?$/;
                if (req.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多只能保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        // integral_price: [
        //   {
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       if (!value) {
        //         callback(new Error("请填写积分参考价"));
        //       } else {
        //         let req = /^\d+(\.\d{1,2})?$/;
        //         if (req.test(value)) {
        //           callback();
        //         } else {
        //           callback(new Error("最多只能保留两位小数"));
        //         }
        //       }
        //     },
        //     trigger: "change",
        //   },
        // ],
        // integral_scale: [
        //   {
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       if (!value) {
        //         callback(new Error("请填写积分参考手续费"));
        //       } else {
        //         let req = /^[0-9]+$/;
        //         if (req.test(value)) {
        //           callback();
        //         } else {
        //           callback(new Error("必须是整数"));
        //         }
        //       }
        //     },
        //     trigger: "change",
        //   },
        // ],
        // voucher_price: [
        //   {
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       if (!value) {
        //         callback(new Error("请填写提货券参考价"));
        //       } else {
        //         let req = /^\d+(\.\d{1,2})?$/;
        //         if (req.test(value)) {
        //           callback();
        //         } else {
        //           callback(new Error("最多只能保留两位小数"));
        //         }
        //       }
        //     },
        //     trigger: "change",
        //   },
        // ],
        // voucher_scale: [
        //   {
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       if (!value) {
        //         callback(new Error("请填写提货券参考手续费"));
        //       } else {
        //         let req = /^[0-9]+$/;
        //         if (req.test(value)) {
        //           callback();
        //         } else {
        //           callback(new Error("必须是整数"));
        //         }
        //       }
        //     },
        //     trigger: "change",
        //   },
        // ],
      },
      for_user_infoForm: {
        pay_type: 1,
        sales_multiplier: "",
        related_user_tag: "",
        related_user_group: "",
        area_id: "",
        is_restricted: 0,
        daily_purchase_limit: "",
        total_purchase_limit: "",
        is_recommendation: 0,
      },
      related_user_tag: [],
      related_user_group: [],
      cascaderRegList: [],
      invitation_relationship: [],
      for_user_infoRules: {
        type: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请选择支付类型"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        sales_multiplier: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入销售倍数区间"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        related_user_tag: [
          {
            required: false,
            validator: (rule, value, callback) => {
              callback();
              // if (this.related_user_tag.length == 0) {
              //   callback(new Error("请关联用户标签"));
              // } else {
              //   callback();
              // }
            },
            trigger: "change",
          },
        ],
        related_user_group: [
          {
            required: false,
            validator: (rule, value, callback) => {
              callback();
              // if (this.related_user_tag.length == 0) {
              //   callback(new Error("请关联用户标签"));
              // } else {
              //   callback();
              // }
            },
            trigger: "change",
          },
        ],
        invitation_relationship: [
          {
            required: false,
            validator: (rule, value, callback) => {
              callback();
              // if (this.related_user_tag.length == 0) {
              //   callback(new Error("请关联用户标签"));
              // } else {
              //   callback();
              // }
            },
            trigger: "change",
          },
        ],
        area_id: [
          {
            required: false,
            validator: (rule, value, callback) => {
              callback();
              // if (this.related_user_tag.length == 0) {
              //   callback(new Error("请关联用户标签"));
              // } else {
              //   callback();
              // }
            },
            trigger: "change",
          },
        ],
        is_recommendation: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
        is_restricted: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
        daily_purchase_limit: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (this.for_user_infoForm.is_restricted == 1) {
                if (value <= 0) {
                  callback(new Error("每日限购数量不能为空"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        total_purchase_limit: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (this.for_user_infoForm.is_restricted == 1) {
                if (value <= 0) {
                  callback(new Error("用户总限购数量不能为空"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      for_mer_infoForm: {
        pay_type: 3,
        selection_limit: [],
        change_price_limit: {
          type: 1,
          values: {
            increment: "",
            decrement: "",
          },
        },
      },
      increment: "",
      decrement: "",
      selectLoading: false,
      for_mer_infoRules: {
        type: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (value == "") {
                callback(new Error("请选择提货类型"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        sales_multiplier: [
          {
            required: false,
            validator: (rule, value, callback) => {
              callback();
              // if (this.for_mer_infoForm.selection_limit.length == 0) {
              //   callback(new Error("请选择当前可选商户"));
              // } else {
              //   callback();
              // }
            },
            trigger: "change",
          },
        ],
        increment: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                this.for_mer_infoForm.change_price_limit.type !== 3 &&
                this.for_mer_infoForm.change_price_limit.type !== 4
              ) {
                return callback();
              }
              if (this.increment == "") {
                callback(new Error("请填写可增加比例"));
              } else {
                let req = /^[0-9]+$/;
                if (req.test(this.increment)) {
                  callback();
                } else {
                  callback(new Error("必须是整数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        decrement: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                this.for_mer_infoForm.change_price_limit.type !== 3 &&
                this.for_mer_infoForm.change_price_limit.type !== 5
              ) {
                return callback();
              }
              if (this.decrement == "") {
                callback(new Error("请填写可减少比例"));
              } else {
                let req = /^[0-9]+$/;
                if (req.test(this.decrement)) {
                  callback();
                } else {
                  callback(new Error("必须是整数"));
                }
              }
            },
            trigger: "change",
          },
        ],
      },
      tableRefs: new Set(),
      cascaderRefs: new Set(),
    };
  },
  created() {
    getCategoryList().then((res) => {
      this.typeDataList = res.data;
    });
    getDictionaryTypeList({ type: "pay_type" }).then((res) => {
      this.payTypeList = res.data;
    });
    getTagCategoryAll().then((res) => {
      this.labelList = res.data;
    });
    getgroupList().then((res) => {
      this.userGroupList = res.data.list;
    });
    getRegionList().then((res) => {
      this.regionList = res.data;
    });
    getMerchantList({ page: 1, count: 20 }).then((res) => {
      this.MerchantList = res.data.list;
    });
    getUserList({ page: 1, count: 10 }).then((res) => {
      this.userList = res.data.list;
    });
    this.getSupplierLists();
    this.getSupplierListWay();
    this.$nextTick(() => {
      if (this.$route.query.id) {
        this.id = this.$route.query.id;
        this.getGoodsInfo(this.$route.query.id);
      }
    });
  },
  methods: {
    // 获取供应商列列表
    async getSupplierLists() {
      const res = await supplierLists();
      const { code, data, message } = res;
      if (code === 200) {
        this.supplierList = data;
      } else {
        this.$message.error(message);
      }
    },
    // 重置供应商列表
    resettingSupplier() {
      this.supplierSearchForm = {
        supplier_id: "",
        goods_name: "",
        category_id: "",
        page: 1,
        count: 10,
      };
      this.getSupplierListWay();
    },
    // 获取供应商产品列表
    async getSupplierListWay() {
      this.supplierGoodsListLoading = true;
      const res = await goodslist(this.supplierSearchForm);
      const { code, data, message } = res;
      if (code === 200) {
        data.list.forEach((item) => {
          item.gc_id = "";
        });
        this.supplierGoodsList = data.list;
        this.supplierTotal = res.data.total;
      } else {
        this.$message.error(res.msg);
      }
      this.supplierGoodsListLoading = false;
    },
    getGoodsInfo(id) {
      this.configurationDialog = true;
      this.addLoding = true;
      detailSelection({ id: id })
        .then((res) => {
          getSupplierGoodsInfo({ id: res.data.sku.id }).then((ress) => {
            // console.log(ress, "供货商商品");
            this.SKUform.goodsName = res.data.sg_name;
            this.SKUform.id = res.data.sku.id;
            this.SKUform.inventory = res.data.sku.inventory;
            this.SKUform.take_delivery_price = res.data.sku.take_delivery_price;
            this.SKUform.voucher_price = Number(res.data.sku.voucher_price);
            this.SKUform.gc_id = res.data.sku.gc_id;
            this.gc_id = [];
            var arr = res.data.sku.gc_id.split(",");
            arr.forEach((item) => {
              this.gc_id.push(Number(item));
            });
            this.suggestionForm.retail_price =
              res.data.sku.suggestion_price.retail_price;
            this.suggestionForm.integral_price =
              res.data.sku.suggestion_price.integral_price;
            this.suggestionForm.integral_scale =
              res.data.sku.suggestion_price.integral_scale;
            this.suggestionForm.voucher_price =
              res.data.sku.suggestion_price.voucher_price;
            this.suggestionForm.voucher_scale =
              res.data.sku.suggestion_price.voucher_scale;
            this.for_user_infoForm.pay_type = res.data.for_user_info.pay_type;
            this.for_user_infoForm.sales_multiplier =
              res.data.for_user_info.sales_multiplier;
            this.for_user_infoForm.is_restricted =
              res.data.for_user_info.is_restricted;
            this.for_user_infoForm.daily_purchase_limit =
              res.data.for_user_info.daily_purchase_limit;
            this.for_user_infoForm.total_purchase_limit =
              res.data.for_user_info.total_purchase_limit;
            this.for_user_infoForm.is_recommendation =
              res.data.for_user_info.is_recommendation;

            this.cascaderRegList = JSON.parse(res.data.for_user_info.area_id);
            var arr = res.data.for_user_info.related_user_tag.split(",");
            this.related_user_tag = [];
            arr.forEach((item) => {
              this.related_user_tag.push(Number(item));
            });
            var arr1 = res.data.for_user_info.related_user_group.split(",");
            this.related_user_group = [];
            arr1.forEach((item) => {
              this.related_user_group.push(Number(item));
            });
            this.for_mer_infoForm.pay_type = res.data.for_mer_info.pay_type;
            this.for_mer_infoForm.change_price_limit.type =
              res.data.for_mer_info.change_price_limit.type;
            if (res.data.for_mer_info.change_price_limit.type == 3) {
              this.increment =
                res.data.for_mer_info.change_price_limit.values.increment;
              this.decrement =
                res.data.for_mer_info.change_price_limit.values.decrement;
            } else {
              this.for_mer_infoForm.change_price_limit.values =
                res.data.for_mer_info.change_price_limit.values;
            }

            this.userList = res.data.for_user_info.invitation_relationship_text;
            this.userList.forEach((item) => {
              this.invitation_relationship.push(item.id);
            });
            this.MerchantList = res.data.for_mer_info.selection_limit_text;
            this.for_mer_infoForm.selection_limit = [];
            res.data.for_mer_info.selection_limit_text.forEach((item) => {
              this.for_mer_infoForm.selection_limit.push(Number(item.id));
            });
            this.addLoding = false;
          });
        })
        .catch((err) => {
          this.addLoding = false;
          this.$messages.error(err.msg);
        });
    },
    // 把商品添加到已选商品中
    addSelectedGoodsWay(row) {
      this.configurationDialog = true;
      this.addLoding = true;
      getSupplierGoodsInfo({ id: row.id }).then((res) => {
        this.SKUform.goodsName = res.data.goods_name;
        this.SKUform.sku_name = res.data.goods_product[0].sku_name;
        this.SKUform.sku_Img_Url = res.data.goods_product[0].sku_img;
        this.SKUform.id = res.data.goods_product[0].id;
        this.SKUform.take_delivery_price =
          res.data.goods_product[0].retail_price;
        this.addLoding = false;
      });
    },
    // 下拉框搜索调用
    remoteMethodWay(query) {
      if (query !== "") {
        this.selectLoading = true;
        getMerchantList({ page: 1, count: 20, user_cellphone: query }).then(
          (res) => {
            this.selectLoading = false;
            this.MerchantList = res.data.list;
          }
        );
      }
    },
    remoteUserMethodWay(query) {
      this.selectLoading = true;
      getUserList({
        search_type: 3,
        search_name: query,
        page: 1,
        count: 10,
      }).then((res) => {
        this.selectLoading = false;
        this.userList = res.data.list;
      });
    },
    // 点击下一步执行
    nextStep() {
      if (this.activeName == "商品规格") {
        this.$refs.SKUform.validate((valid, i) => {
          if (valid) {
            this.$refs.suggestionForm.validate((res, err) => {
              if (res) {
                this.activeName = "针对用户的规则";
              } else {
                this.$messages.error(err.voucher_price[0].message);
                return false;
              }
            });
          } else {
            this.$messages.error(i.voucher_price[0].message);
            return false;
          }
        });
      } else if (this.activeName == "针对用户的规则") {
        this.$refs.for_user_infoForm.validate((valid, i) => {
          if (valid) {
            this.activeName = "针对商户的规则";
          } else {
            this.$messages.error(i.sales_multiplier[0].message);
            return false;
          }
        });
      } else if (this.activeName == "针对商户的规则") {
        this.$refs.for_mer_infoForm.validate((valid, i) => {
          if (valid) {
            this.submitForm();
          } else {
            this.$messages.error(i.decrement[0].message);
            return false;
          }
        });
      }
    },
    submitForm() {
      var bool = true;
      this.$refs.SKUform.validate((valid, err) => {
        if (valid) {
          return true;
        } else {
          this.activeName = "商品规格";
          this.$messages.error(err.voucher_price[0].message);
          bool = false;
          return false;
        }
      });
      this.$refs.suggestionForm.validate((valid, err) => {
        if (valid) {
          return true;
        } else {
          this.activeName = "商品规格";
          this.$messages.error(err.voucher_price[0].message);
          bool = false;
          return false;
        }
      });
      if (!bool) {
        return false;
      }
      this.$refs.for_user_infoForm.validate((valid, err) => {
        if (valid) {
          return true;
        } else {
          this.activeName = "针对用户的规则";
          this.$messages.error(err.sales_multiplier[0].message);
          bool = false;
          return false;
        }
      });
      if (!bool) {
        return false;
      }
      this.$refs.for_mer_infoForm.validate((valid, err) => {
        if (valid) {
          return true;
        } else {
          this.activeName = "针对商户的规则";
          this.$messages.error(i.decrement[0].message);
          bool = false;
          return false;
        }
      });
      if (!bool) {
        return false;
      }
      this.SKUform.gc_id = this.gc_id.toString();
      this.for_user_infoForm.related_user_tag =
        this.related_user_tag.toString();
      this.for_user_infoForm.related_user_group =
        this.related_user_group.toString();
      this.for_user_infoForm.area_id = JSON.stringify(this.cascaderRegList);
      this.for_mer_infoForm.selection_limit =
        this.for_mer_infoForm.selection_limit.toString();
      this.for_user_infoForm.invitation_relationship =
        this.invitation_relationship.toString();
      if (this.for_mer_infoForm.change_price_limit.type !== 3) {
        this.for_mer_infoForm.change_price_limit.values = "0";
      }
      if (this.for_mer_infoForm.change_price_limit.type == 3) {
        this.for_mer_infoForm.change_price_limit.values = {
          increment: this.increment,
          decrement: this.decrement,
        };
      }
      this.addLoding = true;
      if (this.id) {
        var obj = {
          id: this.id,
          sku: {
            ...this.SKUform,
            suggestion_price: {
              ...this.suggestionForm,
            },
          },
          for_user_info: {
            ...this.for_user_infoForm,
          },
          for_mer_info: {
            ...this.for_mer_infoForm,
          },
        };
        editselection(obj)
          .then((res) => {
            if (res.code !== 200) {
              this.addLoding = false;
              return this.$messages.error(res.msg);
            }
            this.$messages.success(res.msg);
            this.addLoding = false;
            this.configuratioClose;
            this.$router.go(-1);
          })
          .catch((err) => {
            this.addLoding = false;
            this.$messages.error(err.msg);
          });
      } else {
        var obj = {
          id: this.id,
          sku: [
            {
              ...this.SKUform,
              suggestion_price: {
                ...this.suggestionForm,
              },
            },
          ],
          for_user_info: {
            ...this.for_user_infoForm,
          },
          for_mer_info: {
            ...this.for_mer_infoForm,
          },
        };
        addselection(obj)
          .then((res) => {
            if (res.code !== 200) {
              this.addLoding = false;
              return this.$messages.error(res.msg);
            }
            this.$messages.success(res.msg);
            this.addLoding = false;
            this.configurationDialog = false;
            this.configuratioClose;
          })
          .catch((err) => {
            this.addLoding = false;
            this.$messages.error(err.msg);
          });
      }
    },
    // 关闭控制器弹框
    configuratioClose() {
      this.SKUform = {
        goodsName: "",
        id: "",
        inventory: "",
        take_delivery_price: "",
        voucher_price: "",
        gc_id: "",
      };
      this.gc_id = [];
      this.suggestionForm = {
        retail_price: "",
        integral_price: "",
        integral_scale: "",
        voucher_price: "",
        voucher_scale: "",
      };
      this.related_user_tag = [];
      this.related_user_group = [];
      this.cascaderRegList = [];
      this.for_user_infoForm = {
        pay_type: 1,
        sales_multiplier: "",
        related_user_tag: "",
        related_user_group: "",
        area_id: "",
        is_restricted: 0,
        daily_purchase_limit: "",
        total_purchase_limit: "",
        is_recommendation: 0,
      };
      this.for_mer_infoForm = {
        pay_type: 3,
        selection_limit: [],
        change_price_limit: {
          type: 1,
          values: {
            increment: "",
            decrement: "",
          },
        },
      };
      if (this.id) {
        this.gobackWay();
        return;
      }
      this.configurationDialog = false;
      this.activeName = "商品规格";
      this.$refs.suggestionForm.resetFields();
      this.$refs.SKUform.resetFields();
      this.$refs.for_user_infoForm.resetFields();
    },

    // 选择供应商商品sku
    async chooseGoodsSku(id) {
      // this.isShowSkuDialog = true
      this.isLoadingSku = true;
      const res = await getGoodsProductList({ GoodsId: id });
      const { data, code, message } = res;
      if (code === 200) {
        data.forEach((item) => {
          item.chooseInventory = 1;
        });
        this.supplierGoodsSkuList = data;
      } else {
        this.$message.error(message);
      }
      this.isLoadingSku = false;
    },
    // 关闭sku弹窗
    closeDialog() {
      this.isShowSkuDialog = false;
    },
    // 多选框发生改变
    handleSelectionChange(val) {
      // console.log('val==>', val)
    },
    // 表格展开事件
    handleExpandChange(row, expandedRows) {
      console.log("row====>", row);
      console.log("expandedRows====>", expandedRows);
      if (expandedRows.length > 0) {
        // 展开
        this.chooseGoodsSku(row.id);
        this.tableRefs.add(row.id);
      }
    },
    // 商品类目发生改变
    handleGoodsCategoryChange(value) {
      console.log("value==>", value);
    },
    // 确定添加选品sku
    async doSaveSelectGoods() {
      if (this.tableRefs.size === 0) {
        this.$message.warning("至少选择一个商品的一个sku");
        return;
      }
      const tempObj = {
        sku: [],
      };
      this.tableRefs.forEach((goodsId) => {
        // 当前商品选中的sku列表
        const selectedSku = this.$refs["multipleTable" + goodsId].selection;
        const goods = this.supplierGoodsList.find(
          (item) => goodsId === item.id
        );
        if (!goods.gc_id) {
          this.$message.warning(`请选择商品[${goods.name}]的类目ID`);
          return;
        }
        if (selectedSku.length > 0) {
          selectedSku.forEach((item) => {
            tempObj.sku.push({
              id: item.id,
              inventory: item.chooseInventory,
              gc_id: goods.gc_id,
            });
          });
        }
      });
      const res = await selectionadd(tempObj);
      const { code, message } = res;
      if (code === 200) {
        this.$message.success(message);
      } else {
        this.$message.error(message);
      }
    },
    gobackWay() {
      this.$router.push("/merchant/selecgoods");
    },
    handleChange(vla) {
      console.log(vla);
    },
  },
};
</script>
<style lang='scss' scoped>
.shuttle {
  // height: 800px;
  display: flex;
  justify-content: space-between;

  .divider {
    width: 1px;
    height: 100%;
    background-color: #ccc;
  }

  .box {
    // flex: 1;
  }
}

.title {
  font-size: 16px;
  font-weight: 700;
  padding-bottom: 10px;
  border-bottom: 2px solid #ededed;
  margin: 0px 0 20px;
}
</style>
<style lang="scss">
.shuttle {
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
